<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共{{ this.page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
            >导入EXCEL</el-button
          >
          <el-button size="small" type="danger" @click="exportExcel"
            >导出EXCEL</el-button
          >
          <el-button size="small" type="primary" @click="showDialog = true"
            >新增员工</el-button
          >
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="头像" align="center">
            <template v-slot="{ row }">
              <img
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
                @click="opened(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号码" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatEmploy"
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <!-- 作用域插槽+过滤器 -->
            <!-- <template slot-scope="obj">
             {{obj.row.timeOfEntry}} 
            </template> -->
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template v-slot="{ row }">
              <el-switch :value="row.enableState === 1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)"
                >角色</el-button
              >
              <el-button type="text" size="small" @click="delEmploy(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :total="this.page.total"
            :current-page="this.page.page"
            :page-size="this.page.size"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹出层 -->
      <employees-dialog :showDialog.sync="showDialog" />
      <el-dialog title="二维码" :visible.sync="showDialogQrcode">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <assign-role
        :showRoleDialog.sync="showRoleDialog"
        :userId="userId"
        ref="roleInfo"
      />
    </div>
  </div>
</template>

<script>
import { getEmployees, delEmployees } from "@/api/employees";
import employeesDialog from "@/views/employees/components/employeesDialog.vue";
import { formatDate } from "@/filters/index";
import QrCode from "qrcode";
// 引入枚举
import emploteesEnum from "@/api/constant/employees";
import AssignRole from "./components/assign-role.vue";
export default {
  name: "employees",
  components: {
    employeesDialog,
    AssignRole,
  },
  data() {
    return {
      loading: false,
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0,
      },
      showDialog: false,
      showDialogQrcode: false,
      showRoleDialog: false,
      userId: null,
    };
  },
  created() {
    this.getEmployees();
  },
  methods: {
    //获取员工信息
    async getEmployees() {
      this.loading = true;
      const { total, rows } = await getEmployees(this.page);
      this.page.total = total;
      this.list = rows;
      this.loading = false;
    },
    //点击页码更新数据
    changePage(newpage) {
      this.page.page = newpage;
      this.getEmployees();
    },
    //格式化聘用模式
    formatEmploy(row, column, cellValue, index) {
      //寻找1所对应的值,hireType 聘用枚举
      const obj = emploteesEnum.hireType.find((item) => item.id === cellValue);
      return obj ? obj.value : "未知";
    },
    //删除员工信息
    async delEmploy(id) {
      try {
        await this.$confirm("是否删除该员工");
        await delEmployees(id);
        this.$message.success("成功删除");
        this.getEmployees();
      } catch (err) {
        console.log(err);
      }
    },
    //导出Excel
    exportExcel() {
      const headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      //懒加载导出
      import("@/vendor/Export2Excel").then(async (excel) => {
        // 获取员工所有资料
        const { rows } = await getEmployees({ page: 1, size: this.page.total });
        const data = this.formatDate(headers, rows);
        const multiHeader = [["姓名", "主要信息", "", "", "", "", "部门"]];
        const merges = ["A1:A2", "B1:F1", "G1:G2"];
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data: data,
          filename: "员工资料表",
          multiHeader, // 复杂表头
          merges, // 合并选项
          // header: ["姓名", "手机"],
          // data: [["黄而过", "1313"]],
          // filename: "员工资料表",
        });
      });
    },
    opened(url) {
      if (url) {
        this.showDialogQrcode = true;
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url);
        }); //将地址转化为二维码
      } else {
        this.$message.warning("该用户还没有上传头像");
      }
    },
    //封装一个处理员工资料信息的方法
    formatDate(headers, rows) {
      return rows.map((item) => {
        return Object.keys(headers).map((key) => {
          // 处理时间格式化
          if (
            headers[key] === "timeOfEntry" ||
            headers[key] === "correctionTime"
          ) {
            return formatDate(item[headers[key]]);
          } else if (headers[key] === "formOfEmployment") {
            const obj = emploteesEnum.hireType.find(
              (same) => same.id === item[headers[key]]
            );
            return obj ? obj.value : "未知";
          }
          return item[headers[key]];
        });
      });
    },
    async editRole(id) {
      this.userId = id;
      await this.$refs.roleInfo.getStaffInfo(id);
      this.showRoleDialog = true;
    },
  },
};
</script>

<style>
</style>